package com.obsidian.free.slideshow;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RemoteViews;
import android.widget.TextView;

public class SlideshowConfigureImages extends Activity implements OnClickListener {

   final static private int MODE_INVALID = -1;

   GridView grid;
   Button back, next;
   ImageAdapter adapter;
   TextView header;

   int mode, appWidgetId, size;
   boolean edit;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.images);

      size = getIntent().getIntExtra("size", SlideshowUpdateService.SIZE_SMALL);
      mode = getIntent().getIntExtra("type", MODE_INVALID);
      edit = getIntent().getBooleanExtra("edit", false);
      if(mode == MODE_INVALID) {
         setResult(RESULT_CANCELED);
         finish();
         return;
      }
      appWidgetId = getIntent().getIntExtra("appWidgetId", AppWidgetManager.INVALID_APPWIDGET_ID);

      adapter = new ImageAdapter(this);

      grid = (GridView)findViewById(R.id.ImagesPageGrid);
      back = (Button)findViewById(R.id.ImagesPageBackButton);
      next = (Button)findViewById(R.id.ImagesPageNextButton);
      header = (TextView)findViewById(R.id.ImagePageCountText);

      grid.setAdapter(adapter);
      grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            launchMenu(position);
         }
      });

      back.setOnClickListener(this);
      next.setOnClickListener(this);
      
      ImageDatabase db = new ImageDatabase(this);
      if(!edit) {
         Log.d("Slideshow", "Not editing");
         next.setEnabled(false);
         db.createWidget(appWidgetId, SlideshowConfigure.TYPE_LOCAL, 0, "", "", 0);
      }else{
         Log.d("Slideshow", "Editing");
         Bundle bundle = db.getWidgetImages(appWidgetId);
         Bitmap[] bmps = (Bitmap[])bundle.getParcelableArray("images");
         adapter.clear();
         for(Bitmap image : bmps) {
            adapter.add(image);
         }
         if(adapter.getCount() > 0)
         header.setText(String.format(getText(R.string.config_images_count).toString(),
               adapter.getCount()));
      }
      db.close();
   }
   
   @Override
   protected void onResume() {
      grid.invalidate();
      grid.invalidateViews();
      next.setEnabled(adapter.getCount() > 0);
      if(adapter.getCount() > 0)
      header.setText(String.format(getText(R.string.config_images_count).toString(),
            adapter.getCount()));
      super.onResume();
   }
   
   @Override
   protected void onSaveInstanceState(Bundle outState) {
      outState.putParcelableArray("images", adapter.toArray());
      super.onSaveInstanceState(outState);
   }
   
   @Override
   protected void onRestoreInstanceState(Bundle savedInstanceState) {
      Bitmap[] images = (Bitmap[])savedInstanceState.getParcelableArray("images");
      adapter.clear();
      for(Bitmap image : images) {
         adapter.add(image);
      }
      header.setText(String.format(getText(R.string.config_images_count).toString(),
            adapter.getCount()));
      super.onRestoreInstanceState(savedInstanceState);
   }
   
   @Override
   public boolean onPrepareOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      menu.clear();
      switch(mode) {
      case SlideshowConfigure.TYPE_LOCAL:
         inflater.inflate(R.menu.images_local, menu);
         break;
      case SlideshowConfigure.TYPE_FLICKR:
         inflater.inflate(R.menu.images_flickr, menu);
         break;
      }
      return super.onPrepareOptionsMenu(menu);
   }

   @Override
   public boolean onMenuItemSelected(int featureId, MenuItem item) {
      int dim = 0;
      switch(size) {
         case SlideshowUpdateService.SIZE_SMALL:
            dim = 200;
            break;
         case SlideshowUpdateService.SIZE_MEDIUM:
            dim = 350;
            break;
         case SlideshowUpdateService.SIZE_LARGE:
            dim = 400;
            break;
      }
      if(mode == SlideshowConfigure.TYPE_LOCAL) {
         switch(item.getItemId()) {
            case R.id.ImagesLocalAdd:
               Intent grab = new Intent(Intent.ACTION_GET_CONTENT, null);
               grab.setType("image/*");
               grab.putExtra("crop", "true");
               grab.putExtra("aspectX", 1);
               grab.putExtra("aspectY", 1);
               grab.putExtra("outputX", dim);
               grab.putExtra("outputY", dim);
               grab.putExtra("noFaceDetection", true);
               grab.putExtra("return-data", true);
               
               startActivityForResult(grab, SlideshowConfigure.REQUEST_IMAGES);
               break;
         }
      }else if(mode == SlideshowConfigure.TYPE_FLICKR) {
         
      }
      return super.onMenuItemSelected(featureId, item);
   }

   public void onClick(View v) {
      ImageDatabase db = new ImageDatabase(this);
      switch(v.getId()) {
      case R.id.ImagesPageBackButton:
         if(!edit) {
            db.deleteWidget(appWidgetId);
         }
         db.close();
         setResult(RESULT_CANCELED);
         finish();
         break;
      case R.id.ImagesPageNextButton:
         Intent intent = new Intent(this, SlideshowConfigureLocal.class);
         intent.putExtra("size", size);
         intent.putExtra("appWidgetId", appWidgetId);
         intent.putExtra("edit", edit);
         startActivityForResult(intent, 10);
         break;
      }
   }
   
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(requestCode == 10 && resultCode == RESULT_OK) {
         RemoteViews view = SlideshowUpdateService.buildUpdate(this, appWidgetId);
         AppWidgetManager manager = AppWidgetManager.getInstance(this);
         manager.updateAppWidget(appWidgetId, view);
         Log.d("Slideshow", "Initial update");
         setResult(RESULT_OK);
         finish();
      }else if(requestCode == 20 && resultCode == RESULT_OK) {
         int action = data.getIntExtra("action", -1);
         int position = data.getIntExtra("position", -1);
         if(position < 0) return;
         ImageDatabase db = new ImageDatabase(this);
         Bundle bundle;
         Bitmap[] bmps;
         switch(action) {
            case SlideshowConfigureImagesOptions.ACTION_DELETE:
               adapter.deletePosition(position);
               db.deleteImage(appWidgetId, position);
               if(adapter.getCount() > 0)
                  header.setText(String.format(getText(R.string.config_images_count).toString(),
                        adapter.getCount()));
               else
                  header.setText(getText(R.string.config_images_empty));
               break;
            case SlideshowConfigureImagesOptions.ACTION_NEXT:
               db.moveImage(appWidgetId, position, 1);
               bundle = db.getWidgetImages(appWidgetId);
               bmps = (Bitmap[])bundle.getParcelableArray("images");
               adapter.clear();
               for(Bitmap image : bmps) {
                  adapter.add(image);
               }
               break;
            case SlideshowConfigureImagesOptions.ACTION_PREV:
               db.moveImage(appWidgetId, position, -1);
               bundle = db.getWidgetImages(appWidgetId);
               bmps = (Bitmap[])bundle.getParcelableArray("images");
               adapter.clear();
               for(Bitmap image : bmps) {
                  adapter.add(image);
               }
               break;
         }
         db.close();
         grid.invalidate();
         grid.invalidateViews();
      }else{
         if(resultCode == RESULT_OK) {
            Bitmap bitmap = (Bitmap)data.getParcelableExtra("data"); 
            
            ImageDatabase db = new ImageDatabase(this);
            db.setWidgetCurrent(appWidgetId, db.setImage(appWidgetId, -1, bitmap));
            adapter.add(bitmap);
            db.close();
            header.setText(String.format(getText(R.string.config_images_count).toString(),
                                         adapter.getCount()));
         }
      }
   }
   
   private void launchMenu(int position) {
      Intent intent = new Intent(this, SlideshowConfigureImagesOptions.class);
      intent.putExtra("position", position);
      startActivityForResult(intent, 20);
   }
}
